package com.medata.filter;

import com.medata.dataObject.BlackListForIp;
import com.medata.repository.BlackListForIpRepository;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author ：zb
 * @date ：Created in 2019/3/26 0026 10:24
 * @description： 黑名单功能,限制ip登入
 */
@WebFilter(urlPatterns = "/*")
public class BlackIpFilter implements Filter {
    @Autowired
    private BlackListForIpRepository repository;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String ip=servletRequest.getRemoteAddr();
        List<BlackListForIp> blackIp = repository.findByBlackIp(ip);
        if (blackIp==null||blackIp.size()==0){
            System.out.println(ip);
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            servletResponse.setCharacterEncoding("GBK");
            PrintWriter out=servletResponse.getWriter();
            out.println("<b>你的ip地址被禁止访问</b>");
        }
    }

    @Override
    public void destroy() {

    }
}
